<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var solveNQueens = function (n) {
        const chessboard = new Array(n).fill().map(() => new Array(n).fill('.'))
        const res = []
        function transformChessboard(chessboard) {
          return chessboard.map(item => item.join(''))
        }
        function backTracking(row) {
          if (row == n) {
            return res.push(transformChessboard(chessboard))
          }
          for (let j = 0; j < n; j++) {
            if (isValid(row, j, chessboard, n)) {
              chessboard[i][j] = 'Q'
              backTracking(row + 1)
              chessboard[i][j] = '.'
            }
          }
        }
        backTracking(0)
        return res
        function isValid(row, col, chessboard, n) {
          //判断是否同行重复
          for (let j = 0; j < col; j++) {
            if (chessboard[row][j] == 'Q') return false
          }
          for (let i = 0; i < row; i++) {
            if (chessboard[i][col] == 'Q') return false
          }
          //判断45°
          for (let i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
            if (chessboard[i][j] == 'Q') return false
          }
          for (let i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
            if (chessboard[i][j] == 'Q') return false
          }
          return true
        }
      }
    </script>
  </body>
</html>
